package cn.pku.sirx.snad.uias.dao.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.Assert;

import cn.pku.sirx.snad.ad.dao.impl.DaoImpl;
import cn.pku.sirx.snad.uias.dao.IFriendDao;
import cn.pku.sirx.snad.uias.model.entity.Friend;

/**
 * @author WangXiao
 */
public class FriendDaoImpl extends DaoImpl<Friend> implements IFriendDao {

	public FriendDaoImpl() {
		super(Friend.class);
	}

	@Override
	public boolean isFriend(String fromUserId, String toUserId) {
		if (fromUserId == null || toUserId == null) {
			return false;
		}

		DetachedCriteria criteria = DetachedCriteria.forClass(targetClass);
		criteria.add(Restrictions.eq("id", fromUserId));
		criteria.add(Restrictions.eq("owner", toUserId));
		return getCount(criteria) > 0;
	}

	@Override
	public int getCommonFriendsCount(String user1Id, String user2Id) {
		Assert.notNull(user1Id);
		Assert.notNull(user2Id);
		if (user1Id.equals(user2Id)) {
			return getFriendCount(user1Id);
		}

		Set<String> user1FriendSet = getFriendIdSet(user1Id);
		Set<String> user2FriendSet = getFriendIdSet(user2Id);
		int result = 0;
		for (String string : user2FriendSet) {
			if (user1FriendSet.contains(string)) {
				++result;
			}
		}
		return result;
	}

	@Override
	public int getFriendCount(String userId) {
		Assert.notNull(userId);

		DetachedCriteria criteria = DetachedCriteria.forClass(targetClass);
		criteria.add(Restrictions.eq("owner", userId));
		return getCount(criteria);
	}

	@Override
	public Set<String> getFriendIdSet(String userId) {
		Assert.notNull(userId);

		DetachedCriteria criteria = DetachedCriteria.forClass(targetClass);
		criteria.add(Restrictions.eq("owner", userId));
		List<Friend> friends = get(criteria);
		Set<String> result = new HashSet<String>();
		for (Friend friend : friends) {
			result.add(friend.getId());
		}
		return result;
	}

}
